package seventhDay.removeNthFromEnd;

public class GetIntersectionNode {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode nodeA = headA;
        ListNode nodeB = headB;
        while (nodeB.next != null && nodeA.next != null){
            if (nodeA == nodeB){
                return nodeA;
            }
            nodeB = nodeB.next;
            nodeA = nodeA.next;
        }
        if (nodeA == nodeB){
            return nodeA;
        }
        if (nodeA.next != null){
            nodeB = headA;
            nodeA = nodeA.next;
        }else if (nodeB.next != null){
            nodeA = headB;
            nodeB = nodeB.next;
        }else {
            return null;
        }
        while (nodeB.next != null && nodeA.next != null){
            nodeB = nodeB.next;
            nodeA = nodeA.next;
        }
        if (nodeA.next != null){
            nodeB = headA;
            nodeA = nodeA.next;
        }else if (nodeB.next != null){
            nodeA = headB;
            nodeB = nodeB.next;
        }
        while (nodeB.next != null && nodeA.next != null && nodeA != nodeB){
            nodeB = nodeB.next;
            nodeA = nodeA.next;
        }
        if (nodeA == nodeB){
            return nodeA;
        }else {
            return null;
        }
    }
}
